import { atom } from 'jotai';

/**
 * 用户信息类型定义
 */
export interface UserInfo {
  id: string;
  username: string;
  lastLoginAt: string;
  loginCount: number;
}

/**
 * 会话信息类型定义
 */
export interface SessionInfo {
  sessionId: string;
  expiresIn: number;
  loginTime: string;
}

/**
 * 用户状态类型定义
 */
export interface UserState {
  isAuthenticated: boolean;
  user: UserInfo | null;
  session: SessionInfo | null;
  loading: boolean;
}

/**
 * 初始用户状态
 */
const initialUserState: UserState = {
  isAuthenticated: false,
  user: null,
  session: null,
  loading: true,
};

/**
 * 用户状态 atom
 */
export const userStateAtom = atom<UserState>(initialUserState);

/**
 * 设置用户登录状态的 atom
 */
export const setUserLoginAtom = atom(
  null,
  (_get, set, { user, session }: { user: UserInfo; session: SessionInfo }) => {
    set(userStateAtom, {
      isAuthenticated: true,
      user,
      session,
      loading: false,
    });
  }
);

/**
 * 设置用户登出状态的 atom
 */
export const setUserLogoutAtom = atom(null, (_get, set) => {
  set(userStateAtom, {
    isAuthenticated: false,
    user: null,
    session: null,
    loading: false,
  });
});

/**
 * 设置加载状态的 atom
 */
export const setLoadingAtom = atom(null, (get, set, loading: boolean) => {
  const currentState = get(userStateAtom);
  set(userStateAtom, {
    ...currentState,
    loading,
  });
});

/**
 * 只读的用户信息 atom
 */
export const userInfoAtom = atom((get) => get(userStateAtom).user);

/**
 * 只读的认证状态 atom
 */
export const isAuthenticatedAtom = atom((get) => get(userStateAtom).isAuthenticated);

/**
 * 只读的加载状态 atom
 */
export const isLoadingAtom = atom((get) => get(userStateAtom).loading);

/**
 * 只读的会话信息 atom
 */
export const sessionInfoAtom = atom((get) => get(userStateAtom).session);

/**
 * 检查会话是否即将过期的 atom
 */
export const isSessionNearExpiryAtom = atom((get) => {
  const session = get(sessionInfoAtom);
  if (!session) return false;

  const loginTime = new Date(session.loginTime).getTime();
  const expiryTime = loginTime + session.expiresIn;
  const currentTime = Date.now();
  const timeUntilExpiry = expiryTime - currentTime;

  // 如果剩余时间少于30分钟，认为即将过期
  return timeUntilExpiry < 30 * 60 * 1000;
});

/**
 * 获取会话剩余时间的 atom
 */
export const sessionTimeRemainingAtom = atom((get) => {
  const session = get(sessionInfoAtom);
  if (!session) return 0;

  const loginTime = new Date(session.loginTime).getTime();
  const expiryTime = loginTime + session.expiresIn;
  const currentTime = Date.now();

  return Math.max(0, expiryTime - currentTime);
});

/**
 * 刷新用户会话的 atom
 */
export const refreshSessionAtom = atom(
  null,
  async (get, set) => {
    const currentState = get(userStateAtom);
    if (!currentState.isAuthenticated) return;

    try {
      const response = await fetch("/api/sso/refresh", {
        method: "POST",
        credentials: "include",
      });

      const data = await response.json();

      if (data.success && data.data) {
        set(setUserLoginAtom, {
          user: data.data.user || currentState.user!,
          session: data.data.sessionInfo || currentState.session!
        });
        console.log("会话刷新成功");
      }
    } catch (error) {
      console.error("会话刷新失败:", error);
    }
  }
);
